package wyd.handler;

import com.alibaba.fastjson2.JSON;
import com.wyd.common.Result;
import com.wyd.exception.GlobalErrorCodeConstants;
import com.wyd.exception.ServiceException;
import org.apache.log4j.Logger;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@ControllerAdvice
public class ExceptionHandler {

	/** 日志实例 */
	private static final Logger logger = Logger.getLogger(ExceptionHandler.class);
	
	@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    @ResponseBody
    public Result defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
		Result r = new Result();
		r.setCode(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode());
    	r.setMsg(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getMsg());
    	e.printStackTrace();
        logger.error("接口异常：", e);
		return r;
    }

	@org.springframework.web.bind.annotation.ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Result MissingServletRequestParameterExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
		Result r = new Result();
		r.setCode(GlobalErrorCodeConstants.PARAM_SERVER_ERROR.getCode());
		r.setMsg(GlobalErrorCodeConstants.PARAM_SERVER_ERROR.getMsg());
    	e.printStackTrace();
        logger.error("缺少必要参数", e);
		return r;
    }

	/**
	 * 自定义的异常
	 * @param request
	 * @param response
	 * @param e
	 * @return
	 */
	@org.springframework.web.bind.annotation.ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result ParseExceptionHandler(HttpServletRequest request, HttpServletResponse response, ServiceException e) {
		Result r = new Result();
		r.setCode(e.getCode());
    	r.setMsg(e.getMessage());
    	logger.error(JSON.toJSONString(r), e);
		return r;
    }
	
	
	
}
